<template>
	<view>
		<div id="localbox" :data901="data901" :change:data901="vedio.case901">
		</div>

		<div id="remotebox" :data902="data902" :change:data902="vedio.case902">
		</div>

		<view class="top" :data903="data903" :change:data903="vedio.case903">
			<image src="../../../static/overturn.png" @click="vedio.changeCamera" :data904="data904"
				:change:data904="vedio.case904" style="width: 80rpx;height: 80rpx" mode="aspectFit"></image>
		</view>

		<!-- 接听、挂断 -->
		<view class="bottom">
			<image src="../../../static/hangUp.png" @click="hangUp" style="width: 100rpx;height: 100rpx"
				mode="aspectFit"></image>
			<image src="../../../static/answer.png" @click="answer" v-if="getAnswer"
				style="width: 100rpx;height: 100rpx" mode="aspectFit"></image>
		</view>

	</view>

</template>
<script>
	import permision from "@/js_sdk/wa-permission/permission.js";
	import {
		socket
	} from '../../../utils/socket.js';
	export default {
		data() {
			return {
				getAnswer: true,
				windowHeight: "",
				initlocal: null,
				fromId: "",
				toId: "",
				data901: null,
				data902: null,
				data903: null,
				data904: null,
				random: 0
			}
		},
		async onLoad(e) {
			this.fromId = e.fromId;
			this.toId = e.toId;

			if (e.type == "to") {
				this.getAnswer = false;
				var message = {
					type: 1,
					fromId: Number(this.fromId),
					toId: Number(this.toId),
					msgType: 900
				}
				socket.send(JSON.stringify(message))
			}

			uni.getSystemInfo({
				success: res => {
					this.windowHeight = res.windowHeight;
				}
			});

			socket.getMessage(res => {
				if (JSON.parse(res.data).fromId == this.toId) {
					let data = JSON.parse(res.data)

					switch (data.msgType) {
						case 901:

							this.random = this.random + 1;
							this.data901 = data.message + this.random;
							break;
						case 902:

							this.data902 = data.message;
							break;
						case 903:

							this.data903 = data.message;
						case 904:

							this.data904 = data.message;
							break;
						case 905:

							uni.navigateBack();
							break;
					}
				}

			})
		},
		methods: {
			answer() {
				var message = {
					type: 1,
					fromId: Number(this.fromId),
					toId: Number(this.toId),
					message: "901",
					msgType: 901
				}
				socket.send(JSON.stringify(message));
				this.getAnswer = false;
			},
			hangUp() {
				var message = {
					type: 1,
					fromId: Number(this.fromId),
					toId: Number(this.toId),
					message: "905",
					msgType: 905
				}
				socket.send(JSON.stringify(message))
				uni.navigateBack();
			},
			sendMessage(val) {
				var message = JSON.parse(val);
				message.fromId = Number(this.fromId);
				message.toId = Number(this.toId);
				socket.send(JSON.stringify(message));
			}
		}
	}
</script>

<script module="vedio" lang="renderjs">
	export default {
		data() {
			return {
				video: null,
				remote: null,
				mode: "user",
				mediaStreamTrack: null,
				mystrea: null,
				pc: null,
				rtpSender: null
			}
		},
		mounted(e) {
			this.createVedio();
			this.initVideo();
		},
		methods: {
			createVedio() {
				var localbox = document.getElementById("localbox");
				var localvideo = document.createElement("video");
				localvideo.id = "local";
				localbox.appendChild(localvideo);

				var remotebox = document.getElementById("remotebox");
				var remotevideo = document.createElement("video");
				remotevideo.id = "remote";
				remotebox.appendChild(remotevideo);
			},
			initVideo() {
				let that = this;
				this.video = document.getElementById("local");
				this.remote = document.getElementById("remote");

				setTimeout(() => {
					if (
						navigator.mediaDevices.getUserMedia ||
						navigator.getUserMedia ||
						navigator.webkitGetUserMedia ||
						navigator.mozGetUserMedia
					) {
						//调用用户媒体设备, 访问摄像头
						this.getUserMedia({
								video: {
									width: {
										ideal: 220,
										max: 220
									},
									height: {
										ideal: 140,
										max: 140
									},
									facingMode: this.mode,
									frameRate: {
										ideal: 30,
										min: 10
									}
								},
								audio: {
									noiseSuppression: true,
									echoCancellation: true
								}
							},
							this.videoSuccess,
							this.videoError
						);
					} else {}
				}, 300);
			},

			getUserMedia(constraints, success, error) {
				if (navigator.mediaDevices.getUserMedia) {
					//最新的标准API
					navigator.mediaDevices
						.getUserMedia(constraints)
						.then(success)
						.catch(error);
				} else if (navigator.webkitGetUserMedia) {
					//webkit核心浏览器
					navigator.webkitGetUserMedia(constraints, success, error);
				} else if (navigator.mozGetUserMedia) {
					//firfox浏览器
					navigator.mozGetUserMedia(constraints, success, error);
				} else if (navigator.getUserMedia) {
					//旧版API
					navigator.getUserMedia(constraints, success, error);
				}
			},

			videoSuccess(stream) {
				this.video.srcObject = stream;
				this.mystrea = stream;
				this.video.play();
			},

			videoError(error) {
				console.log('摄像头获取错误')
			},

			case901(newValue, oldValue, ownerVm, vm) {
				if (newValue != null) {
					if (this.pc == null) {
						this.createPeerConnection();
					} else {
						this.pc.removeTrack(this.rtpSender);
						this.createPeerConnection();
					}

					this.pc.createOffer(this.createOfferAndSendMessage, this.handleCreateOfferError)
				}
			},

			case902(newValue, oldValue, ownerVm, vm) {
				if (newValue != null) {
					if (this.pc == null) {
						this.createPeerConnection()
					} else {
						this.pc.removeTrack(this.rtpSender);
						this.createPeerConnection();
					}

					this.pc.setRemoteDescription(new RTCSessionDescription(newValue));
					this.doAnswer()
				}
			},

			case903(newValue, oldValue, ownerVm, vm) {
				if (newValue != null) {
					this.pc.setRemoteDescription(new RTCSessionDescription(newValue));
				}
			},

			case904(newValue, oldValue, ownerVm, vm) {
				if (newValue != null) {
					var candidate = new RTCIceCandidate({
						sdpMLineIndex: newValue.sdpMLineIndex,
						candidate: newValue.candidate
					});
					this.pc.addIceCandidate(candidate)
				}
			},

			createOfferAndSendMessage(sessionDescription) {
				this.pc.setLocalDescription(sessionDescription)
				var message = {
					type: 1,
					msgType: 902,
					message: sessionDescription,
					createTime: Date.now()
				}
				this.$ownerInstance.callMethod('sendMessage', JSON.stringify(message));
			},

			handleCreateOfferError() {
				console.log("handleCreateOfferError error");
			},

			doAnswer() {
				if (this.pc == null) {
					this.createPeerConnection()
				}

				this.pc.createAnswer().then(this.createAnswerAndSendMessage, this.handleCreateAnswerError);
			},

			createAnswerAndSendMessage(sessionDescription) {

				this.pc.setLocalDescription(sessionDescription)
				var message = {
					type: 1,
					msgType: 903,
					message: sessionDescription,
					createTime: Date.now()
				}
				this.$ownerInstance.callMethod('sendMessage', JSON.stringify(message));
			},

			handleCreateAnswerError() {
				console.log("handleCreateAnswerError error")
			},

			createPeerConnection() {
				this.pc = new RTCPeerConnection(null);
				this.pc.onicecandidate = this.handleIceCandidate;
				this.pc.onaddstream = this.handleRemoteStreamAdded;
				for (const trac of this.mystrea.getTracks()) {
					this.rtpSender = this.pc.addTrack(trac, this.mystrea);
				}

			},

			handleIceCandidate(event) {
				var message = {
					type: 1,
					msgType: 904,
					message: event.candidate,
					createTime: Date.now()
				}
				if (event.candidate) {
					this.$ownerInstance.callMethod('sendMessage', JSON.stringify(message));
				}
			},

			handleRemoteStreamAdded(event) {
				this.remote.srcObject = event.stream;
				this.remote.play()
			},

			changeCamera() {
				this.mode = this.mode === 'user' ? 'environment' : 'user';
				this.initVideo();
				setTimeout(() => {
					this.$ownerInstance.callMethod('answer', "901");
				}, 1000);
			}
		}
	}
</script>

<style>
	* {
		margin: 0;
		padding: 0;
	}

	#localbox {
		position: absolute;
		right: 0;
		top: 20px;
		width: 120px;
		height: 150px;
		z-index: 100;
		cursor: move;
	}

	#remotebox {
		position: absolute;
		left: 0;
		top: 0;
		width: 100%;
		height: 100%;
		z-index: 1;
	}

	#local {
		position: absolute;
		width: 100%;
		height: 100%;
		z-index: 100;
		object-fit: cover;
		cursor: move;
	}

	#remote {
		position: absolute;
		width: 100%;
		height: 100%;
		z-index: -1;
		object-fit: cover;
	}

	#turn {
		position: absolute;
		width: 50px;
		left: 100px;
		z-index: 200;
	}

	.top {
		width: 80rpx;
		height: 80rpx;
		position: absolute;
		display: flex;
		flex-direction: row;
		justify-content: space-around;
		z-index: 888;
		top: 20px;
		left: 20px;
	}

	.bottom {
		width: 750rpx;
		height: 100rpx;
		position: absolute;
		display: flex;
		flex-direction: row;
		justify-content: space-around;
		z-index: 888;
		bottom: 100rpx;
	}
</style>